package com.jt.demos;

import com.jt.JedisDataSource;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.util.List;

/**
 * redis秒杀练习：
 *   模拟两个线程都去抢购一张票
 */
public class SecondKillDemo2 {
    public static void main(String[] args) {
        Jedis jedis = JedisDataSource.getConnection();
        jedis.set("ticket", "1");
        jedis.set("money", "0");

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                secKill();
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                secKill();
            }
        });

        t1.start();
        t2.start();
    }

    private static void secKill() {
        Jedis jedis = JedisDataSource.getConnection();
        jedis.watch("ticket","money");
        Transaction multi = jedis.multi();
        try {
            multi.decrBy("ticket", 1);
            multi.incrBy("money", 100);
            List<Object> exec = multi.exec();
            System.out.println(exec);
        } catch (Exception e) {
            multi.discard();
            throw e;
        } finally {
            jedis.unwatch();
            jedis.close();
        }

    }
}
